//调用http模块
var http = require('http');
var fs=require('fs');
var path=require('path');
var url=require('url');

var types = {
    "css": "text/css",
    "gif": "image/gif",
    "html": "text/html",
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
    "pdf": "application/pdf",
    "png": "image/png",
    "svg": "image/svg+xml",
    "swf": "application/x-shockwave-flash",
    "tiff": "image/tiff",
    "txt": "text/plain",
    "wav": "audio/x-wav",
    "wma": "audio/x-ms-wma",
    "wmv": "video/x-ms-wmv",
    "xml": "text/xml"
};
var server = http.createServer(function (request, response) {
    response.setHeader('Access-Control-Allow-Origin' ,'*');
    response.setHeader('Access-Control-Allow-Methods' ,'GET, POST,PUT,DELETE, OPTIONS');
    response.setHeader('Access-Control-Allow-Headers' ,'token');
    var pathname = url.parse(request.url).pathname;
    if(pathname=='/'){
    	pathname="/index.html";
    }
    console.log(pathname);
    var realPath = path.join(".", pathname);
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
    console.log("realPath:" +realPath);
    fs.exists(realPath, function (exists) {
        if (!exists || ext=='unknown') {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
           
            fs.stat(realPath, function (err, stat) {
               
                if (err) {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
                    var lastModified = stat.mtime.toUTCString();
                    var ifModifiedSince = request.headers['if-modified-since'];
                    if (lastModified == ifModifiedSince) {
                        response.writeHead(304, "Not Modified");
                        response.end();
                    }else{
                        var contentType = types[ext] || "text/plain";
                        fs.readFile(realPath, function(err, file){
                                response.setHeader("Content-Type",contentType);
                                response.setHeader("Last-Modified",lastModified);
                                response.writeHead(200, "OK");
                                response.end(file);

                        }); 

                    }   
                }
            });
        }
    });
});
server.listen(3003);
//打印日志
console.log('Http server is started. http://www.jrain.org:6152/index.html');
 